<?php
namespace app\admin\controller;
use app\pay\model\User;
use think\Controller;
use think\Db;
use think\facade\Session;
use think\captcha\Captcha;
use app\admin\model\Admin;
use app\admin\model\PayUpgrade;

class Upgrade extends Base{
	public function __construct(){
       parent::__construct();
    }

	public function index()
	{
		$model = model("PayUpgrade");
		if ($this->request->isAjax()) {
			$page = input("page");
			$limit = input("limit");
			$where = $this->create_index_where();

			$list = $model->where($where)->page($page, $limit)->order("upgrade_time desc")->fetchSql(0)->select();
			//halt($list);
			$count = $model->where($where)->count("upgrade_id");
			foreach ($list as $k => $val) {
				$val["payment_name"] = Db::name("payment")->where(["payment_id" => $val["upgrade_pay_id"]])->value("payment_name");
				$val["upgrade_type_id"] = Db::name("user_type")->where(["type_id" => $val["upgrade_type_id"]])->value("type_name");
			}
			$tongji = $model->getTotalMoney(true);

			return json(["code" => 0, "count" => $count, "data" => $list, "msg" => "", "total_money" => $tongji["totalMoney"],"profit_money"=>$tongji["profitMoney"]]);
		} else {
			$typeList = Db::name("user_type")->select();
			$this->assign("typeList", $typeList);
			return $this->fetch();
		}
	}


	/**
	 * 订单搜索数据验证
	 *
	 * @param  [type] $data [description]
	 *
	 * @return [type]       [description]
	 * @author yan  2018-01-16
	 */
	public function create_index_where()
	{
		$data = $this->request->param();
		$where = array();
		$getdata = array();

		// 用户ID
		if (isset($data['phone']) && !empty($data['phone'])) {
			$uid = Db::name('user')->where(array('user_phone' => $data['phone']))->value("user_id");
			if ($uid) {
				$where[] = array('upgrade_uid', '=', $uid);
				$getdata['phone'] = $data['phone'];
			} else {
				$where[] = array('upgrade_uid', '=', '');
				$getdata['phone'] = $data['phone'];
			}
		}

		//支付状态
		if (isset($data['state']) && $data['state'] != "") {
			$where[] = array('upgrade_state', '=', $data['state']);
			$getdata['state'] = $data['state'];
		}
		//订单号
		if (isset($data['form_no']) && !empty($data['form_no'])) {
			$where[] = array('upgrade_form_no', '=', $data['form_no']);
			$getdata['form_no'] = $data['form_no'];
		}
		//上游订单号
		if (isset($data['sn']) && !empty($data['sn'])) {
			$where[] = array('upgrade_sn', '=', $data['sn']);
			$getdata['sn'] = $data['sn'];
		}

		//通道名称
		if (isset($data['type_id']) && !empty($data['type_id'])) {
			$where[] = array('upgrade_type_id', '=', $data['type_id']);
			$getdata['type_id'] = $data['type_id'];
		}

		//时间搜索
		$query_date = input('query_date', '', 'trim,htmlspecialchars');
		if (!empty($query_date)) {
			$query_date = explode(" - ", $query_date);
			$query_date[0] = strtotime($query_date[0]);
			$query_date[1] = strtotime($query_date[1] . "+1day");
			$where[] = ['upgrade_time', 'between', $query_date];
			$getdata['query_date'] = $data['query_date'];
		}
		//halt($where);


		$res['where'] = $where;
		$res['getdata'] = $getdata;
		return $where;
	}
    
    /*
     * 未支付订单修改为成功并修改状态
     * 2018年8月30日11:08:50
     * 刘媛媛
     */
    public function supply(){
    	
    	$id = input('get.id',0);
       
        if(!$id){
        	return json(['error'=>1,'msg'=>'参数错误']);
        }
        
        $upData = Db::name('payUpgrade')->where('upgrade_state',0)->where(array('upgrade_id'=>$id))->find();
        if(!$upData){
            return json(['error'=>1,'msg'=>'订单不存在或状态不允许此操作']);
        }
        Db::startTrans();
		try {
		    Db::name('payUpgrade')->where(array('upgrade_id'=>$upData['upgrade_id']))->update(['upgrade_state'=>1,'upgrade_oktime'=>time(),'upgrade_sn'=>time().'系统后台补单']);
		      	
		    Db::name('user')->where('user_id',$upData['upgrade_uid'])->update(['user_type_id'=>$upData['upgrade_type_id']]);
		   
          	//修改费率
            update_rate($upData['upgrade_uid'],$upData['upgrade_type_id']);
          	
           // 提交事务
		    Db::commit();
		     return json(['error'=>0,'msg'=>'操作成功']);
		} catch (\Exception $e) {
		    // 回滚事务
		    Db::rollback();
		    return json(['error'=>1,'msg'=>'操作失败']);
		}
       	
       	return json(['error'=>1,'msg'=>'操作失败ERROR']);
    }
    /*
     * 删除订单操作
     * 2018年8月30日11:15:07
     * 刘媛媛
     */
    public function delete(){
    	$id = input('get.id',0);
       
        if(!$id){
        	return json(['error'=>1,'msg'=>'参数错误']);
        }
        
        $upData = Db::name('payUpgrade')->where(array('upgrade_id'=>$id))->find();
        if(!$upData){
            return json(['error'=>1,'msg'=>'订单不存在']);
        }
        
        Db::name('payUpgrade')->where(array('upgrade_id'=>$id))->delete();
    	return json(['error'=>0,'msg'=>'删除成功']);
    }
    
    /*
     * 自动升级
     * 2018年8月30日11:15:34
     * 刘媛媛
     */
    public function upgrade(){
    	
    	if($this->request->isPost()) {
    		$id		  = input('get.uid',0);
	       	$userData = Db::name('user')->where(array('user_id'=>$id))->find();
	        if(!$userData){
	            return json(['error'=>1,'msg'=>'会员不存在']);
	        }
    		$type	  = input('post.type',0);//升级目标
    		$state	  = input('post.state',0);//关系升级|免费升级
    		$liyou	  = input('post.liyou');//升级理由
    		$typeData = Db::name('userType')->where(array('type_id'=>$type))->find();
    		
    		if(!$typeData){
    			return json(['error'=>1,'msg'=>'升级不存在']);
    		}
    		
    		if($userData['user_type_id']==$type){
    			return json(['error'=>1,'msg'=>'不能升级相同的类型']);
    		}

            Db::name('user')->where(array('user_id'=>$userData['user_id']))->update(['user_type_id'=>$type]);
            $upgrade = array();
            $upgrade['upgrade_uid'] 	= $userData['user_id'];
            $upgrade['upgrade_pay_id']  = 0;
            $upgrade['upgrade_form_no'] = 'system'.time();
            $upgrade['upgrade_sn'] 		= $liyou;
            $upgrade['upgrade_money']   = 0;
            $upgrade['upgrade_type_id'] = $type;
            $upgrade['upgrade_state']   = $state;
            $upgrade['upgrade_time'] 	= time();
            $upgrade['upgrade_oktime']  = time();
            Db::name('payUpgrade')->insert($upgrade);

            //修改会员费率
            update_rate($upgrade['upgrade_uid'],$upgrade['upgrade_type_id']);
            //判断平级挂到平台下边
			$userModel = (new User());
			$pinfo = $userModel->where(["user_id"=>$userData["user_pid"]])->find();
			if(empty($pinfo)){//没有上级不返
				return json(['error'=>0,'msg'=>'升级成功']);
			}
			$user = $userData;
			$user_id = $id;
			$old_pid = $pinfo["user_id"];
			$userlist = $userModel->where(["user_state" => 0])->field("user_id,user_pid,user_type_id,user_name")->order("user_id asc")->select();
			$pinfo=[];

			for($i=($type+1);$i<=4;$i++){
				//var_dump($i);
				$ulist = (new User())->getGaoLev($userlist,$user["user_pid"],$i);
				$pinfo = $ulist[0];
				//var_dump($pinfo);
				if(!empty($pinfo)){
					break;
				}
			}
			//halt($pinfo);
			if(!empty($pinfo)){
				//挂到高等级下级
				$userModel->where(["user_id" => $user_id])->update(["user_pid" => $pinfo["user_id"], "user_old_pid" => $old_pid]);
			}else{
				//挂到平台
				$userModel->where(["user_id" => $user_id])->update(["user_pid" => 0, "user_old_pid" => $old_pid]);
			}
            return json(['error'=>0,'msg'=>'升级成功']);
    	}
    	$id 		= input('get.uid',0);
       	$userData   = Db::name('user')->where(array('user_id'=>$id))->find();
        if(!$userData){
           $isUser  = '不存在';
        }else{
        	$isUser = '存在';
        }
        
        $listType = Db::name('userType')->cache('3600')->select();
    	$this->assign('listType',$listType);
        $this->assign('isUser',$isUser);
    	$this->assign('userData',$userData);
    	return $this->fetch();
    }
    
}